package com.lej.my

import android.content.res.Resources
import android.widget.LinearLayout
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.lej.core.base.BaseActivity
import com.lej.core.base.statusHeight
import com.lej.core.common.PCacheInfo
import com.lej.core.common.Params
import com.lej.core.router.CRouter
import com.lej.core.utils.extention.collectOwner
import com.lej.core.utils.extention.getFragmentByRoute
import com.lej.core.utils.extention.toLink
import com.lej.core.utils.load
import com.lej.core.widget.drawable.stateDrawable
import com.lej.dataservice.club.http.bean.onSuccess
import com.lej.my.databinding.MyActivityMyBinding
import com.lej.my.databinding.MyHomeItemTabBinding
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.layout.QMUIButton
import com.qmuiteam.qmui.util.QMUIStatusBarHelper

/**
 *  author: cjq
 *  date  : 2022/6/9 0009
 *  desc  :
 */
@Route(path = CRouter.newmy)
class MyActivity : BaseActivity<MyActivityMyBinding, MyViewModel>() {
    private var unReadCompoundNum = 0

    override fun getLayout(): Int = R.layout.my_activity_my

    override fun initVariableId(): Int = BR.vm

    override fun initData() {
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        val index = intent?.getIntExtra(Params.INDEX, 1) ?: 1
        val tabArray =
            arrayOf(
                MyTabData.INFORMATION,
                MyTabData.SERVICE,
                MyTabData.SETTINGS,
                MyTabData.ABOUT,
                MyTabData.LOGOUT,
            )
        tabArray.forEachIndexed(::addTab)
        binding.viewpager.adapter = MyAdapter(
            this,
            tabArray.filter { it.route.isNotEmpty() && it.url.isEmpty() }.toTypedArray()
        )
        binding.viewpager.isUserInputEnabled = false
        binding.viewpager.setCurrentItem(index, false)
        viewModel.selectTab.value = index
        binding.ivBack.onClick { finish() }
        getUserInfo()
    }

    private fun addTab(index: Int, item: MyTabData) {
        binding.llMenu.apply {
            val itemTabBinding: MyHomeItemTabBinding =
                DataBindingUtil.inflate(layoutInflater, R.layout.my_home_item_tab, null, false)
            itemTabBinding.apply {
                setPadding(
                    statusHeight + 10,
                    paddingTop,
                    paddingRight,
                    paddingBottom
                )
            }
            itemTabBinding.ll.onClick {
                if (unReadCompoundNum > 0 && item.title == "数字文创") {
                    viewModel.sendHadRead()
                    setUnReadNum(0, "数字文创")
                }

                if (item.url.isEmpty()) {
                    binding.viewpager.setCurrentItem(index, false)
                    return@onClick
                }
                toLink(item.url)
            }

            itemTabBinding.iv.setImageDrawable(
                context.stateDrawable(def = item.normalId, select = item.selectId)
            )
            itemTabBinding.tv.text = item.title
            itemTabBinding.root.tag = item.title
            addView(itemTabBinding.root)


        }
    }

    fun setUserName(nick:String){
        binding.tvName.text = nick
    }

    override fun onResume() {
        super.onResume()
        viewModel.getUnreadMsg().onSuccess(this) {
            val num = it.get("num").asInt
            val compoundNum = it.get("unread_compose_num").asInt
            unReadCompoundNum = compoundNum
            setUnReadNum(compoundNum, "数字文创")
            setUnReadNum(num, "求购通知")
        }
    }

    private fun getUserInfo() {
        viewModel.initUSerInfo().onSuccess(this) { info ->
            setUserName(info.nick)
            PCacheInfo.nick = info.nick
            PCacheInfo.imId = info.tencent_id ?: ""
            PCacheInfo.imToken = info.tencent_user_sig ?: ""
            PCacheInfo.userId = info.id
            PCacheInfo.headImg = info.avatar
            PCacheInfo.isAuth = info.isAuthentication()
            load(
                info.avatar,
                R.drawable.ic_load_place,
                R.drawable.ic_load_place_error,
                binding.ivHead
            )
        }
    }

    override fun initViewObservable() {
        viewModel.selectTab.collectOwner(this, ::refurbishItem)
        binding.viewpager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                viewModel.selectTab.value = position
            }
        })
    }

    private fun setUnReadNum(num: Int, viewStr: String) {
        var view: QMUIButton? = null
        for (index in 0 until binding.llMenu.childCount) {
            val layout: LinearLayout = binding.llMenu.getChildAt(index) as LinearLayout
            if (layout.tag == viewStr) {
                view = layout.getChildAt(layout.childCount - 1) as QMUIButton
            }
        }
        view?.isVisible = num != 0
        view?.text = num.toString()
    }


    private fun refurbishItem(selectIndex: Int) {
        for (index in 0 until binding.llMenu.childCount) {
            val layout: LinearLayout = binding.llMenu.getChildAt(index) as LinearLayout
            layout.children.forEach { it.isSelected = selectIndex == index }
        }
    }

    class MyAdapter(fm: FragmentActivity, private val tabs: Array<MyTabData>) :
        FragmentStateAdapter(fm) {
        override fun getItemCount() = tabs.size

        override fun createFragment(position: Int) = tabs[position].route.getFragmentByRoute()
    }

}